# -*- coding:utf-8 -*-
"""
# 文件读写基础函数，包含读和写操作
# 使用try的方式处理编码问题，首先采用utf-8编解/码，如果出错，再尝试gbk，还不行，使用windows默认的mbcs编码
# 在极端情况下可能会形成乱码
"""


def file_read(path):
    """read text from .xw case file"""
    try:
        with open(path) as f:
            data = f.read()
            f.close()
            try:
                result = data.decode('utf-8')
            except:
                try:
                    result = data.decode('gbk')
                except:
                    try:
                        result = data.decode('mbcs')
                    except Exception, e:
                        return '<Error>Read File Decode Error:' + str(e)
            return result

    except Exception as err:
        print '<Error>Read File Error:' + str(err), path
        return '<Error>Read File Error:' + str(err)


def file_write(path, data):
    """try to encode data firstly, avoid write file error and case an empty file"""
    try:
        try:
            result = data.encode('utf-8')
        except:
            try:
                result = data.encode('gbk')
            except:
                try:
                    result = data.encode('mbcs')
                except Exception, e:
                    result = '<Error>Fail To Write File:' + str(e)
        if result.startswith('<Error>'):
            print result + u'\npath: ' + path
            return result
        f = open(path, "w")
        f.write(result)
        f.close()
        return 'Success To Write File!'
    except Exception as err:
        print '<Error>Write File Error:' + str(err)
        return '<Error>fail to write file:' + str(err)
